package bTree.LeetCode;

import java.util.Arrays;

public class 合并区间 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        int[][] res = new int[intervals.length][2];
        int cnt = 0;
        int start = intervals[0][0], end = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            int left = intervals[i][0], right = intervals[i][1];
            if (left > end) {
                res[cnt][0] = start;
                res[cnt][1] = end;
                start = left;
                end = right;
                cnt++;
            } else if (right > end) {
                end = right;
            }
        }
        res[cnt][0] = start;
        res[cnt][1] = end;
        return Arrays.copyOfRange(res,0,cnt+1);
    }
}